Skip to content

[中文版本](/posts/c教程/zh-CN/05-输入输出与文件/042-File Pointers and fopen fclose)

Files let your C programs remember things beyond runtime. Unlike standard input and output, which disappear when the program ends, files provide persistent storage, you can read and write data between runs.

This section introduces the key file-handling API in C:fopen(),fclose(),fprintf(),fscanf(), and their relatives.

The Big Picture ​

File I/O in C uses aFILE * pointer to represent an open file. You don’t manipulate the disk directly, instead, you read and write through a buffered file stream managed by the runtime.

FILE *fp = fopen("data.txt", "r");

This returns a pointer to aFILE object if successful, orNULL if the file can’t be opened.

File Modes ​

When opening a file, you specify a mode, what you intend to do with it.

ModeMeaningBehavior
"r"readFails if file doesn’t exist
"w"writeCreates new or truncates existing
"a"appendOpens or creates; writes go to end
"r+"read/writeMust exist
"w+"read/writeTruncates if exists
"a+"read/writeAppends; reading starts at beginning

Tiny Code: Write and Read a File ​

#include <stdio.h>
int main(void) {
    FILE *fp = fopen("example.txt", "w");
    if (!fp) {
        perror("Failed to open file");
        return 1;
    }
    fprintf(fp, "Hello, file world!\n");
    fprintf(fp, "C makes you closer to the machine.\n");
    fclose(fp);
    fp = fopen("example.txt", "r");
    if (!fp) {
        perror("Failed to reopen file");
        return 1;
    }
    char line[100];
    printf("--- File Content ---\n");
    while (fgets(line, sizeof(line), fp))
        printf("%s", line);
    fclose(fp);
    return 0;
}

Output:

--- File Content ---
Hello, file world!
C makes you closer to the machine.

How It Works ​

  1. fopen() creates a connection to a file.
  2. fprintf() writes formatted text, just likeprintf() but to a file stream.
  3. fclose() flushes buffers and closes the file.
  4. Reopen with"r" mode to read what you wrote.

You can also mix withfscanf() to read formatted data.

Checking for Errors ​

Always check file operations for errors. Useif (!fp) afterfopen(), and useperror() to print the reason.

FILE *f = fopen("missing.txt", "r");
if (!f) {
    perror("Error opening file");
}

Example output:

Error opening file: No such file or directory

Reading Formatted Data with fscanf ​

You can parse text files usingfscanf(), just likescanf():

#include <stdio.h>
int main(void) {
    FILE *fp = fopen("numbers.txt", "r");
    if (!fp) return 1;
    int a, b;
    while (fscanf(fp, "%d %d", &a, &b) == 2)
        printf("%d + %d = %d\n", a, b, a + b);
    fclose(fp);
    return 0;
}

Ifnumbers.txt contains:

2 3
10 15
7 9

Output:

2 + 3 = 5
10 + 15 = 25
7 + 9 = 16

File Position and Rewinding ​

You can move around a file using:

fseek(fp, 0, SEEK_SET);  // go to beginning
fseek(fp, 0, SEEK_END);  // go to end
rewind(fp);              // reset to start

To know where you are:

long pos = ftell(fp);
printf("Current position: %ld\n", pos);

Writing Binary Data ​

Text files are human-readable; binary files store raw bytes. You’ll usefwrite() andfread() for that (covered more in the next section).

Example:

int numbers[] = {1, 2, 3, 4};
fwrite(numbers, sizeof(int), 4, fp);

Why It Matters ​

File I/O is the bridge between your C program and the real world:

  • Configuration and log files
  • Database storage
  • Caches and serialization
  • Operating system utilities (copy, move, grep, etc.)

It teaches resource management, alwaysfopen() andfclose() in pairs, check errors, and handle failures gracefully.

Try It Yourself ​

  1. Write a program that asks for your name and saves it touser.txt.
  2. Append a timestamp each time the program runs.
  3. Read all lines and count how many times your program has been executed.
  4. Modify the example to reverse all lines read from a file.
  5. Handle missing files gracefully usingperror().

You now know how to open, read, and write text files safely. Next, you’ll go deeper into binary files, where data moves in raw bytes, perfect for storing structs and arrays efficiently.

本站总访问 — 次